import { useUserStore } from '@/store/user'
const userStore = useUserStore()
const { dict } = userStore
// 获取字典数据和字典值翻译

// 获取某个类型字典数据-列表
export function queryDictByList(dictCode) {
  let dictList = null
  if (dict[dictCode]) {
    dictList = dict[dictCode]
  }
  return dictList || []
}
// 获取某个类型字典数据-树型
export function queryDictByTree(dictCode) {
  let dictTree = null
  if (dict[dictCode]) {
    const list = JSON.parse(JSON.stringify(dict[dictCode]))
    dictTree = this.listTranslateToTree(list)
  }
  return dictTree || []
}

// 树形数据转换
export function listTranslateToTree(data, id = 'id', pid = 'parentId') {
  let res = []
  let temp = {}
  for (let i = 0; i < data.length; i++) {
    temp[data[i][id]] = data[i]
  }
  for (let k = 0; k < data.length; k++) {
    if (temp[data[k][pid]] && data[k][id] !== data[k][pid]) {
      if (!temp[data[k][pid]]['children']) {
        temp[data[k][pid]]['children'] = []
      }
      if (!temp[data[k][pid]]['_level']) {
        temp[data[k][pid]]['_level'] = 1
      }
      data[k]['_level'] = temp[data[k][pid]]._level + 1
      temp[data[k][pid]]['children'].push(data[k])
    } else {
      res.push(data[k])
    }
  }
  return res
}
/**
 * 获取字典值
 * @param {*} dictConfig 字典列表：数组，多个字典；字符串，一个字典
 * @param {*} value 查询的值
 * @param {*} multiple 是否多选
 * @param {*} isTree 是否树形结构
 */
export function getDictValue(dictConfig, value, multiple, isTree) {
  // 获取字典
  let dict = []
  if (typeof dictConfig === 'string') {
    dict = queryDictByList(dictConfig)
  } else {
    dictConfig.forEach((item) => {
      dict = dict.concat(queryDictByList(item))
    })
  }

  // 循环字典获取字典中文值
  if (multiple) {
    const valueArr = value ? value.split(',') : []
    const labelArr = []
    for (let val of valueArr) {
      for (let item of dict) {
        if (val === item.value) {
          labelArr.push(item.name)
          break
        }
      }
    }
    return isTree ? labelArr.join('-') || value : labelArr.join('、') || value
  } else {
    const valueStr =
      value !== null && value !== undefined ? value.toString() : ''
    let label = value
    for (let item of dict) {
      if (item.value === valueStr) {
        label = item.name
        break
      }
    }
    return label
  }
}
/**
 * 获取字典样式
 * @param {*} dictConfig 字典列表：数组，多个字典；字符串，一个字典
 * @param {*} value 查询的值
 * @param {*} isTag 是否是ELTage组件，需要特殊处理
 */
export function getDictStyle(dictConfig, value) {
  // 获取字典
  let dict = []
  if (typeof dictConfig === 'string') {
    dict = queryDictByList(dictConfig)
  } else {
    dictConfig.forEach((item) => {
      dict = dict.concat(queryDictByList(item))
    })
  }

  const valueStr = value !== null && value !== undefined ? value.toString() : ''
  let style = ''
  for (let item of dict) {
    if (item.value === valueStr) {
      style = item.className || item.styleName
      break
    }
  }
  return style
}
